package com.scs.application.core.pdf.json;

import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.scs.application.core.pdf.enums.PdfPageDirection;
import com.scs.application.core.pdf.enums.SpacingMode;
import com.scs.application.core.pdf.enums.TextShowType;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.layout.property.TextAlignment;

import java.lang.reflect.Field;
import java.lang.reflect.Type;

/**
 * @description:
 */
public class EnumDeserializer implements ObjectDeserializer {

    @Override
    public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {

        Object value = parser.parse();
        String strValue = null;
        if (value instanceof String) {
            strValue = (String) value;
        }

        if (type == PdfPageDirection.class) {
            return (T) PdfPageDirection.of(strValue);
        }

        if (type == PageSize.class) {
            try {
                Field field = PageSize.class.getField(strValue.toUpperCase());
                return (T) field.get(PageSize.class);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                return (T) PageSize.Default;
            }
        }

        if (type == SpacingMode.class) {
            return (T) SpacingMode.of(strValue);
        }

        if (type == TextShowType.class) {
            return (T) TextShowType.of(strValue);
        }
        if (type == TextAlignment.class) {
            TextAlignment[] values = TextAlignment.values();
            for (TextAlignment textAlignment : values) {
                if (textAlignment.name().equals(strValue)) {
                    return (T) textAlignment;
                }
            }
        }


        return (T) value;
    }

    @Override
    public int getFastMatchToken() {
        return 0;
    }

}
